from dds import Creat,conn,cursor
import pymysql
import hashlib
class Users(object):
    __slots__ = ('uid','username','usertype','password','regtime','fl','email')
    def __init__(self,fl=False):
        self.fl=fl
    def add_user(self):       #添加用户
        name=input('请输入用户名：')
        utype=input('请输入用户类型（普通用户或者管理员）：')
        password=input('请输入密码：')
        email=input('请输入邮箱：')
        self.username = name
        self.usertype = utype
        self.password = password
        self.email=email
        # 密码签名存储
        passwords = hashlib.sha1(self.password.encode('utf8')).hexdigest()
        if len(self.username)<=2 or len(self.username.strip(' '))==0:
            print('用户名不符合规则,请重新输入!')
        else:
            try:
                sql='''insert into user(username,usertype,password,email) values(%s,%s,%s,%s);
                    '''
                Creat.switch() #切换用户
                cursor.execute(sql,(self.username,self.usertype,passwords,self.email))
                conn.commit()
            except Exception as e:
                print(e)
                print('用户名已存在，请重新输入！')
                self.add_user()



    def login(self):             #用户登录
        name=input('请输入用户名：')
        password=input('请输入密码：')
        password=hashlib.sha1(password.encode('utf8')).hexdigest()
        Creat.switch()
        sql='select username,password from user;'
        # pymysql.cursors.DictCursor 返回的数据：[{},{}]
        cursor2=conn.cursor(pymysql.cursors.DictCursor)
        res= cursor2.execute(sql)
        # print(cursor2.fetchall())
        data=[]
        for i in cursor2:
            data.append(i)
        flag=False
        for i in data:
            for j in i:
                if i['username']==name and i['password']==password:
                    print('登陆成功')
                    flag=True
                    self.fl=True
                    break
        if not flag:
            print('密码或⽤户名错误，请重新登录')
            self.login()

    def show(self):   #展示信息
        Creat.switch()
        sql='''select username,usertype,password,regtime,email from user
        '''
        cursor.execute(sql)
        # print(cursor.fetchall())
        for i in cursor:
            print(i)


if __name__=='__main__':
    user=Users()
    #user.login()
    user.add_user()
    user.show()
    conn.close()
    cursor.close()


